/**
 * Connexion Scene
 * @version 1.0
 * @author David Ronai aka Makio
 */
 
var ConnexionScene = function ConnexionScene( camera, scene, render )
{
	Abstract3DScene.call( this, camera, scene, render );
	
	this.clouds = [parseFloat($('#cloud1').css("marginLeft")),
				   parseFloat($('#cloud2').css("marginLeft")),
				   parseFloat($('#cloud3').css("marginLeft")),
				   parseFloat($('#cloud4').css("marginLeft")),
				   parseFloat($('#cloud5').css("marginLeft"))];

	this.clock = 0;
	
	this.init = function init()
	{
		connection = this;
	}
	
	this.transitionIn = function()
	{
		this.initOptionManager();
		this.initAccountUI();
		if(modelLoader.get("logo") == null) {
			this.load3D();
		}
		else{
			this.create3d();
			this.displayAccountUI();
		}
	}
	
	this.load3D = function()
	{
		modelLoader.onProggress = connection.onLoadProgress;
		modelLoader.load({name:"logo", model:"./dae/logo.dae", scale:0.25});
	}
	
	this.onLoadProgress = function(loaded,total) {
		if(loaded/total == 1) {
			modelLoader.onProgress == null;
			connection.create3d();
			connection.displayAccountUI();
		}
	}
	
	this.create3d = function()
	{
		addSpotlight({color:0xFFFFFF, x:-10, y:30, z:100, targetX:-40, targetY:-10, intensity:1, exponent:4, fov:110, far:800, visible:0});
		addSpotlight({color:0xFFFFFF, x:100, y:30, z:100, targetX:40, targetY:-10, intensity:1,exponent:4, fov:110, far:800, visible:0});
		
		// Logo
		connection.logo = modelLoader.get("logo");
		connection.logo.position.y = 23;
		changeOpacity(connection.logo,0);
		connection.enableShading(connection.logo);
		scene.add(connection.logo);
		
		TweenLite.delayedCall(.5,function(){
			var scale = 0.28;
			tweenMaterial(connection.logo,1,{opacity:1});
			TweenLite.to( connection.logo.scale, 2, { x:scale, y:scale, z:scale, ease:Back.easeOut});
		});
	}
	
	this.enableShading = function(d) {
		if(d.material!=undefined){
			d.material.shininess = 300;
			d.material.shading = THREE.SmoothShading;
		}
		if(d.materials!=undefined){
			for(var i=0; i<materials.length; i++){
				materials[i].shading = THREE.SmoothShading;
				materials[i].shininess = 300;
			}
		}
		if(d.children != undefined){
			for(var i=0; i < d.children.length; i++){
				d.children[i].castShadow = true;
				d.children[i].receiveShadow	= true;
				connection.enableShading(d.children[i]);
			}
		}
	}
	
	this.initOptionManager = function()
	{
		$(window).keydown(function(e) { //press space
			if (e.which == 32) {
				e.preventDefault();
				$('#light').fadeToggle();
				updateLightPanelValue();
			}
		});
		
		$('.camera').attr('disabled',true);
		$('#cameraX').change(function(){
			if(!$('#CameraManual').is(':checked'))
				return;
			camera.position.x = parseInt($('#cameraX').val());
		});
		$('#cameraY').change(function(){
			if(!$('#CameraManual').is(':checked'))
				return;
			camera.position.y = parseInt($('#cameraY').val());
		});
		$('#cameraZ').change(function(){
			if(!$('#CameraManual').is(':checked'))
				return;
			camera.position.z = parseInt($('#cameraZ').val());
		});
		$('#cameraRX').change(function(){
			if(!$('#CameraManual').is(':checked'))
				return;
			camera.rotation.x = parseFloat($('#cameraRX').val())*Math.PI/180;
		});
		$('#cameraRY').change(function(){
			if(!$('#CameraManual').is(':checked'))
				return;
			camera.rotation.y = parseFloat($('#cameraRY').val())*Math.PI/180;
		});
		$('#cameraRZ').change(function(){
			if(!$('#CameraManual').is(':checked'))
				return;
			camera.rotation.z = parseFloat($('#cameraRZ').val())*Math.PI/180;
		});
		$('#lookX, #lookY, #lookZ').change(function(){
			if(!$('#CameraManual').is(':checked'))
				return;
			camera.lookAt(new THREE.Vector3(parseInt($('#lookX').val()),parseInt($('#lookY').val()),parseInt($('#lookZ').val())));
		});
		$('#CameraManual').click(function (e){
			if($('#CameraManual').is(':checked')){
				$('.camera').attr('disabled',false);
			} else {
				$('.camera').attr('disabled',true);
			}
		});
		$('#ambient').ColorPicker({
			color: '#fffff',
			onSubmit: function(hsb, hex, rgb, el) {
				$(el).val(hex);
				$(el).ColorPickerHide();
				$(this).val(this.value);
			},
			onBeforeShow: function () {
				$(this).ColorPickerSetColor(this.value);
				connection.changeColorLight();
			},
			onChange: function (hsb, hex, rgb) {
				$('#ambient').val(String(hex).toUpperCase());
				connection.changeColorLight();
			}
		})
		.bind('keyup', function(){
			$(this).ColorPickerSetColor(this.value);
			connection.changeColorLight();
		});
		
		$('#directional').ColorPicker({
			color: '#fffff',
			onSubmit: function(hsb, hex, rgb, el) {
				$(el).val(hex);
				$(el).ColorPickerHide();
				$(this).val(this.value);
			},
			onBeforeShow: function () {
				$(this).ColorPickerSetColor(this.value);
				connection.changeColorLight();
			},
			onChange: function (hsb, hex, rgb) {
				$('#directional').val(String(hex).toUpperCase());
				connection.changeColorLight();
			}
		})
		.bind('keyup', function(){
			$(this).ColorPickerSetColor(this.value);
			connection.changeColorLight();
		});
		
		$('.colorPicker').keydown(function(e) { //press enter
			if (e.which == 13) {
				e.preventDefault();
				connection.changeColorLight();
			}
		});
		
		$('.colorPicker').blur( function(){
			connection.changeColorLight();
		});
	}
	
	this.changeColorLight = function()
	{
		if(ambientlight){
			scene.remove( ambientlight );
		}
		ambientlight = new THREE.AmbientLight( parseInt("0x"+$('#ambient').val()) );
		scene.add( ambientlight );
	}
	
	this.initTwitterFlow = function ()
	{
		var url = "http://search.twitter.com/search.json?q=olympic%20game";
		$.ajax({
		  url: url,
		  dataType: "jsonp",
		  jsonpCallback: "twitterFlowCallback"
		}).error(function()
		{
			$("footer").hide();
		});
	}

	this.twitterFlowCallback = function (data)
	{ 
		var results = data.results;
		var o;
		var div;
		
		for(var i = 0; i < results.length; i++){
			o = results[i];
			div = $(document.createElement('div'));
			div.html(o.text);
			div.addClass("tweet");
			if(i%2==0)
				div.addClass("tweet2");
			div.css({left:parseInt(230*i)+"px"});
			$("footer").append(div);
		}
	}

	this.initAccountUI = function()
	{
		$("#account input[type='text']").click( function(){
			if($(this).val()=="Enter a twitter account"
				||$(this).val()=="Ce compte n'existe pas"
			){ $(this).val(""); }
			$(this).css({color:"#999"});
		});	
		$("#account input[type='text']").blur( function(){
			if($(this).val()=="")
			{
				$(this).val("Enter a twitter account");
				$("#account input[type='submit']").attr("disabled", "true");
			}
			else {$("#account input[type='submit']").removeAttr("disabled", "disabled");}
		});
		$("#account a").click( function(e)
		{
			e.preventDefault();
			connection.submitName();
		});
		$("#account input[type='text']").keydown(function(e) { //press enter
			if (e.which == 13) {
				e.preventDefault();
				connection.submitName();
			}
		});
		
		//rollover sexy effect
		$("#account a").mouseenter(function() {
			TweenLite.to($("#account span"),.3,{css:{height:"24px"}, ease:Quad.easeOut} );
		}).mouseleave(function() {
			TweenLite.to($("#account span"),.3,{css:{height:"0px"}, ease:Quad.easeIn} );
		});
	}
	
	this.displayAccountUI = function(){
		$("#account").show();
		$("#cloud").show();
		for(var i=1; i < 6; i++){
			TweenLite.from($("#cloud"+i),1.5+Math.random()*1.5,{delay:1+Math.random(),css:{"opacity":0}},{css:{"opacity":1}});
		}
		TweenLite.from($("#participate"),.7,{delay:2.5,css:{"opacity":0, height:'125px'}},{css:{"opacity":1, height:'135px'}, ease:Quad.easeOut});
	}

	this.submitName = function ()
	{
		$("#account input").attr("disabled", "true");

		var url = "https://api.twitter.com/1/users/show.json?screen_name="+userName;
		$.ajax({
		  url: url,
		  dataType: "jsonp",
		  jsonpCallback: "accountCallback",
		  timeout:5000,
		  error:function(xhr, status, error){
			$("#account input").removeAttr("disabled", "disabled");
			$("#account input[type='text']").val("Ce compte n'existe pas");
			$("#account input[type='text']").css({color:"#F00"});
		  }
		});
		
		userName = $("#account input[type='text']").val();
	}
	
	this.accountCallback = function(data)
	{
		user = data;
		console.log(data);
		userID = data.id;	
		TweenLite.to(connection.logo.scale, 1,{x:0.23, y:0.23, z:0.23, onComplete:connection.onTransitionOutComplete, ease:Back.easeIn});
		tweenMaterial(connection.logo, .5,{delay:.5,opacity:0});
		TweenLite.to($("#participate"),.7,{ css:{"opacity":0}, ease:Quad.easeIn});
	}
	
	this.onTransitionOutComplete = function(){
		removeAllLight();
		$("#account").hide();
		for(var i=1; i < 6; i++){
			TweenLite.killTweensOf($("#cloud"+i));
		}
		scene.remove(connection.logo);
		scene.remove(userMobile);
		connection.logo = null;
		
		SceneTraveler.getInstance().transitionTo( new SportSelectionScene(camera, scene, renderer) );
	}
	
	this.update = function()
	{
		camera.position.x += ( -80+(1-mouseX/screenWidth) * 80 - camera.position.x ) * .05;
		camera.position.y += ( 70-(1-mouseY/screenHeight) * 70 - camera.position.y ) * .05;
		camera.lookAt( scene.position );
		this.clock += .05;
		
		moveCloud2D($('#cloud1'),0,-.5);
		moveCloud2D($('#cloud2'),1,-.5);
		moveCloud2D($('#cloud3'),2,-.55);
		moveCloud2D($('#cloud4'),3,-.4);
		moveCloud2D($('#cloud5'),4,-.6);
	}
	
	this.dispose = function()
	{
		this.camera = null;
		this.scene = null;
		this.render = null;
		this.state = "";
		this.callback = null;
	}
	
	this.init();
}

ConnexionScene.prototype = new Abstract3DScene();
ConnexionScene.prototype.constructor = ConnexionScene;

function moveCloud2D(cloud,index,vx)
{
	if(connection.clouds[index]< -screenWidth/2-cloud.width() ){
		connection.clouds[index]=screenWidth/2;
	} else if(connection.clouds[index]> screenWidth/2){
		connection.clouds[index]=-screenWidth/2-cloud.width();
	}
	connection.clouds[index] = connection.clouds[index]+vx;
	cloud.css( 'marginLeft', connection.clouds[index] );
}

var connection;

//wrapper
function accountCallback(data){ connection.accountCallback(data); }